var qqmap = require('../../utils/qqmap-wx-jssdk.min.js');
var md5 = require('../../utils/md5.js');
var pickerViewT = 0;
var show = false;
var moveY = 200;
var util = require('../../utils/util.js');
// var add = {};
var photo = {};
const app = getApp()
Page({
  data: {
      publicUrl: app.globalData.publicUrl,
      logo:'/pages/image/photo.jpg',
      chooseSize: false,
      animationData: {},
      sel_fenlei:'选择分类',
      sel_fenlei_f: '',
      value:'',
      indicatorDots: true,
      autoplay: false,
      interval: 5000,
      duration: 2000,
      afterColor:'#ff9800',
      beforeColor:'#ccc',
      dotsClass:['on'],
     // time:'8:30',
      date: util.formatTime(new Date),
      cndate:'选择日期',
      cndate2:'选择日期',
      cndate_f:'',
      xieyi:'我已阅读并同意',
      inputValue:'',
      textareavalue:'',
      money:'',
      address: '',
      isaddress:'1',
      logo:'/pages/image/photo.jpg',
      logo_a:'',
      mobile_f:'',
      check:'',
      phone:'',
      sel_fenlei_fid:'',
      formdata:'',
      cone:'',
  },
  /****
   * 汉风
   * 2019-04-26
   * 发布任务时，暂时不上传图片了
   * 如果将来要上传图片，则把chooseImageTap，chooseWxImage打开即可
   */
  // chooseImageTap: function () {
  //   let _this = this;
  //   wx.showActionSheet({
  //     itemList: ['从相册中选择', '拍照'],
  //     itemColor: "#f7982a",
  //     success: function (res) {
  //       if (!res.cancel) {
  //         if (res.tapIndex == 0) {
  //           _this.chooseWxImage('album')
  //         } else if (res.tapIndex == 1) {
  //           _this.chooseWxImage('camera')
  //         }
  //       }
  //     }
  //   })
  // },
  // chooseWxImage: function (type) {
  //   let _this = this;
  //   wx.chooseImage({
  //     sizeType: ['original', 'compressed'],
  //     sourceType: ['album', 'camera'],
  //     sourceType: [type],
  //     success: function (res) {
  //       console.log(res);
  //       _this.setData({
  //         logo: res.tempFilePaths[0],
  //         logo_a: res.tempFilePaths[0],
  //       })
  //       var tempFilePaths = res.tempFilePaths; 
  //     }
  //   })
  // },
  /*
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var demo = new qqmap({
      key: 'JIRBZ-BQSKX-24Q4W-TF5GS-SOYCH-XUF7H'
    });
    var that = this;
    wx.getLocation({
      type: 'gcj02',  //编码方式，
            success: function(res) {
              var latitude = res.latitude   // wx.getLocation 获取当前的地理位置、速度   latitude(维度)  longitude（经度）
              var longitude = res.longitude
              var accuracy = res.accuracy
          //      console.log(res.longitude, res.latitude);
              demo.reverseGeocoder({
          //腾讯地图api 逆解析方法 首先设计经纬度
               //  hasLocation: true,
                location: {
                  latitude: res.latitude,
                  longitude: res.longitude
                },
          　　　　 //逆解析成功回调函数
                  success: function (res) {
                     getApp().globalData.cityname = res.result.address;   
                      // var address = res.result.formatted_addresses.recommend; 
                      var address = res.result.address;    
                    
                      that.setData({
                        address:address,
                        address_f:address,
                      })
                      console.log('-------位置--------');
                      console.log(address);
                    console.log('-------位置--------');
              },
        });
      },
      //点击取消时表示没有获取，
      fail: function (res) {
        that.setData({
          isaddress: '2'
        })
      },
     });
    //  返回手机号,如果已存在，则返回，否则返回空

  },
  chooseSezi: function (e) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      chooseSize: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  hideModal: function (e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear'
    })
    that.animation = animation
    animation.translateY(200).step()
    that.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        chooseSize: false
      })
    }, 200)
  },
  //选择分类通过接口接收的信息
  onShow: function () {
    /**模拟接收手机号码缓存**/ 
    
   
    var that = this
    wx.request({
      url: that.data.publicUrl + 'type',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success:function(res){
        console.log('123');
        console.log(res.data.data);
        that.setData({
          type:res.data.data
        })
      }
    })
  },
  func: function (e) {
    console.log(e.currentTarget.dataset.fid);
    this.setData({
      sel_fenlei: e.currentTarget.dataset.text,
      sel_fenlei_f: e.currentTarget.dataset.text,
      sel_fenlei_fid: e.currentTarget.dataset.fid,
    })
  },
  intervalChange: function (e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function (e) {
    this.setData({
      duration: e.detail.value
    })
  },
  //移动按钮点击事件
  translate: function (e) {
    if (pickerViewT == 0) {
      moveY = 0;
      show = false;
      pickerViewT = 1;
    } else {
      moveY = 200;
      show = true;
      pickerViewT = 0;
    }
    // this.animation.translate(arr[0], arr[1]).step();
    animationEvents(this, moveY, show);
  },
  //隐藏弹窗浮层
  hiddenFloatView(e) {
    //  console.log(e);
    moveY = 200;
    show = true;
    pickerViewT = 0;
    animationEvents(this, moveY, show);
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    
  },
  //选择服务时间
  bindDateChange:function(e){


    this.setData({
      cndate: e.detail.value,
      cndate_f: e.detail.value
    })
  },
  bindDateChange2: function (e) {


    this.setData({
      cndate2: e.detail.value,
      cndate_f2: e.detail.value
    })
  },
  checkboxChange:function(e){
 
    this.setData({
      check: e.detail.value.length
    })
    console.log(e.detail.value.length);
  },
  //提交判断
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value,
    })
  },
  bindTextAreaBlur:function(e){
    this.setData({
      textareainput: e.detail.value,
    })
  },
  bindmoney:function(e){
    this.setData({
      money:e.detail.value
    })
  },
  mobileInput:function(e){
    this.setData({
      mobile:e.detail.value,
      mobile_f: e.detail.value,
    })
   
  },
  formSubmit: function (e) {
    //  console.log('编码是:'+randomString());
    var that = this;
    var timestamp = Date.parse(new Date());
    var timestamps = timestamp / 1000;
    var formatTime = util.formatTime(new Date);
    var codeLength = 8;
    var code = '';
    var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    for (var i = 0; i < codeLength; i++) {
      var index = Math.floor(Math.random() * 10);
      code += random[index];
    }
    var cone = formatTime + code
    that.setData({
      cone: cone
    })
    // console.log(cone);
    // that.unitedPayRequest(wx.getStorageSync('openid'));
    // console.log('标题：' + e.detail.value.title)
    // console.log('描述: ' + e.detail.value.content)
    // console.log('地址:' + e.detail.value.address)
    // console.log('分类:' + that.data.sel_fenlei_fid)
    // console.log('开始时间:' + e.detail.value.server_time1)
    // console.log('结束时间:' + e.detail.value.server_time2)
    // console.log('电话:' + e.detail.value.mobile)
    // console.log('赏金:' + e.detail.value.money)
    // console.log('图片:'+that.data.logo_a)
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!e.detail.value.title){
      wx.showToast({
        title: '请输入标题！',
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.content){
      wx.showToast({
        title: '请输入具体要求！',
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.address){
      wx.showToast({
        title: '请输入当前位置！',
        icon: 'none',
        duration: 2000
      })
    } else if (!that.data.sel_fenlei_fid){
      wx.showToast({
        title: '请选择分类！',
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.server_time1){
      wx.showToast({
        title: '请选择开始服务时间！',
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.server_time2){
      wx.showToast({
        title: '请选择结束服务时间！',
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.money){
      wx.showToast({
        title: '请输入感谢费！',
        icon: 'none',
        duration: 2000
      })
    }else if(this.data.check != 1){
      wx.showModal({
        title: '',
        content: '未同意用户协议！',
        success: function (res) {
          if (res.confirm) {
            console.log('点击确定！')
          }
        }
      })
    } else{
      var title = e.detail.value.title
      var amount = e.detail.value.money
      that.setData({
        formdata:{
            title: e.detail.value.title,
            content: e.detail.value.content,
            address: e.detail.value.address,
            fenlei: that.data.sel_fenlei_fid,
            server_time1: e.detail.value.server_time1,
            server_time2: e.detail.value.server_time2,
            mobile: e.detail.value.mobile,
            money: e.detail.value.money,
            uid: wx.getStorageSync('uid'),
            fk_number:that.data.cone
        }
      })
      // console.log('---------------------------');
      // console.log(that.data.formdata);
      // console.log('---------------------------');
      that.wxpay(title, amount);
    }
  },
  // 支付方法,传入标题和赏金
  wxpay: function (title, amount){
    var that = this
    var timestamp = Date.parse(new Date());
    var timestamps = timestamp / 1000;
    var formatTime = util.formatTime(new Date);
    var codeLength = 4;
    var code = '';
    var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    for (var i = 0; i < codeLength; i++) {
      //设置随机数范围,这设置为0 ~ 36
      var index = Math.floor(Math.random() * 10);
      //字符串拼接 将每次随机的字符 进行拼接
      code += random[index];
    }
    // 手动拼接订单号
    var cone = formatTime + code
    wx.request({
     // url: 'http://192.168.1.154/wan/public/api/ceshi/wxpay',
      url:'https://huoyou.duostec.com/wxapi/Wxpay/wxpay',
    //  url: 'http://192.168.1.120/huoyou/wxapi/Wxpay/wxpay',
      data: {
        // order_id: codes,
        title: title,
        uid: wx.getStorageSync('uid'),
        openid: wx.getStorageSync('openid'),
        cone: that.data.cone,
        amount: amount,
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }, // 设置请求的 header
      success: function (res) {
          var order = res.data.arr;
          wx.requestPayment({
            timeStamp: order.timeStamp,
            nonceStr: order.nonceStr,
            package: order.package,
            signType: 'MD5',
            paySign: order.paySign,
            success: function (res) {
              // console.log('------------支付成功后的返回------------')
              // console.log(res);
              // console.log('------------------------')
              wx.showToast({
                title: "支付成功!",
                duration: 2000,
              });
              // 上传数据
              if (that.data.logo_a){
                wx.uploadFile({
                  url: that.data.publicUrl+'add_order',
                  filePath: that.data.logo_a,
                  name: 'file',
                  formData: that.data.formdata,
                  success(res) {
                    console.log(res);
                    console.log('上传成功!');
                    wx.navigateTo({
                      url: '/pages/person/person',
                    });
                  },
                  fail(res){
                    console.log('失败');
                  },
                  confirm(res){
                    console.log('完成');
                  }
                })
              }else{
                wx.request({
                  url: that.data.publicUrl + 'add_order',
                  data: that.data.formdata,
                  header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  method: 'POST',
                  success: function (res) {
                    // wx.showToast({
                    //   title: '提交成功',
                    //   icon: none,
                    //   duration: 1500
                    // })
                   
                    wx.navigateTo({
                      url: '/pages/person/person',
                    });
                  },
                  fail: function (res) {
                    wx.showToast({
                      title: '请检查网络是否链接',
                      icon: none,
                      duration: 1500
                    })
                  }
                })
              }

              // 
              
            },
            fail: function (res) {
              console.log(res)
              wx.showToast({
                title: '未支付',
                duration: 3000
              })
            }
          })
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    })
  },
  // 
})
/***选择分类时弹出动画函数****/
function animationEvents(that, moveY, show) {
  // console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  })
  that.animation.translateY(moveY + 'vh').step()
  that.setData({
    animation: that.animation.export(),
    show: show
  })
}
function randomString() {
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  var maxPos = chars.length;
  var pwd = '';
  for (var i = 0; i < 32; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}
function getXMLNodeValue(node_name, xml) {
  var tmp = xml.split("<" + node_name + ">")
  var _tmp = tmp[1].split("</" + node_name + ">")
  return _tmp[0]
}
/* 时间戳产生函数   */
function createTimeStamp() {
  return parseInt(new Date().getTime() / 1000) + ''
}